package com.zmx.job.admin.core.nodedistribute.routestrategy;

import com.zmx.job.admin.core.nodedistribute.NodeWeightInfo;

import java.util.*;

/**
 * @Description: 轮询 加权
 * @ClassName: RoundRobin
 * @Author zhaomxr
 * @Date 2021-12-22 15:36
 */
public class RoundRobinWeight {

    //当前轮询的节点 从0开始
    private static Integer code = 0;

    public static String get() {

        Map<String, Integer> clientInstance = NodeWeightInfo.getClientInstance();

        //使用类内部nodeMap,避免同一时刻客户端上下线 影响当前选举
        Map<String, Integer> nodeMap = new HashMap<String, Integer>(clientInstance.size());
        nodeMap.putAll(clientInstance);

        List<String> nodeList = new ArrayList<>(16);
        for(String node:nodeMap.keySet()){
            //当前节点权重
            Integer weight = nodeMap.get(node);
            // 比如权重为4，那么就将当前节点放入4次
            for (int i=0;i<weight;i++){
                nodeList.add(node);
            }
        }


        String node = "";
        synchronized (code) {
            //如果当前轮询节点已到最大值，从0开始重新计算
            if (code >= nodeList.size()) {
                code = 0;
            }
            node = nodeList.get(code);
            code++;
        }

        return node;
    }
}
